import React, { Component, useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
// 导入的时候加{}，导出的时候会报错
import { Card, Alert, Typography, Button, Form, Input, Row, Col, Select, message } from 'antd';
import ResourceCard from '@/components/ResourceCard';
import FormItem from 'antd/lib/form/FormItem';
import { addLink } from '@/services/ant-design-pro/links';
import { getTags } from '@/services/ant-design-pro/links';
import styles from './index.less';
import axios from 'axios';

const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 5,
    },
    md: {
      span: 4,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
    md: {
      span: 12,
    },
  },
};

const submitFormLayout = {
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
      offset: 5,
    },
    md: {
      span: 8,
      offset: 4,
    },
    lg: {
      span: 7,
      offset: 4,
    },
  },
};

const tags = [];
const res = await getTags();
const temp = res.data;
for (let i = 0; i < temp.length; i++) {
  tags.push(<Option key={temp[i]?.id}>{temp[i]?.tip}</Option>);
}

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

const AddResource = () => {
  const [resource, setResource] = useState('');
  const [hobbys, setHobbys] = useState('');
  const [loading, setLoading] = useState(false);
  const [avator, setAvator] = useState('');
  const [form] = Form.useForm();

  useEffect(() => {
    if (loading === false) {
      getAllTags();
      setLoading(true);
    }
  });

  const onValuesChange = (changedValues, allValues) => {
    const tmpResource = { ...allValues };
    setResource(tmpResource);
  };

  //   提交上传表单
  const doSubmit = (values) => {
    // console.log(values);
    let newValues = values;
    newValues.tips = newValues.tips.map(Number);
    newValues.icon = avator;
    // console.log(newValues);
    addNewLink(newValues);
    // if (!currentUser || !currentUser._id) {
    //   message.error('提交失败，请刷新页面重试！');
    //   return;
    // }
    // values.userId = currentUser._id;
    // values.reviewStatus = reviewStatusEnum.REVIEWING;
  };

  // 上传资源
  const addNewLink = async (values) => {
    try {
      const res = await addLink({ ...values });
      // console.log(res);
      // console.log(res.data.id);
      message.success('上传成功');
    } catch (error) {
      console.log(error);
    }
  };

  // 获得所有标签
  const getAllTags = async () => {
    try {
      const res = await getTags();
      // const temp = res.data;
      for (let i = 0; i < temp.length; i++) {
        tags.push(<Option key={temp[i]?.id}>{temp[i]?.tip}</Option>);
      }
      // console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  function UploadPic() {
    const upload = async ({ target }) => {
      const files = new FormData();
      files.append('file', target.files[0]);
      console.log(target.files[0]);

      const { data } = await axios.post('/api/user/uploadAvator', files, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      // console.log(data.avatorUrl);
      setAvator(data.avatorUrl);
    };
    return (
      <>
        <div>
          <input type="file" onChange={upload} />
        </div>
      </>
    );
  }

  return (
    <div>
      <PageContainer title="推荐资源" content={<span>欢迎推荐优质资源</span>}>
        <Card bordered={false}>
          <Form
            layout="vertical"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              marginTop: 8,
            }}
            form={form}
            name="resource"
            // {...formItemLayout}
            // labelAlign="left"
            // scrollToFirstError
            onValuesChange={onValuesChange}
            loading={loading}
          >
            <FormItem
              label="资源名称"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入资源名',
                },
              ]}
            >
              <Input placeholder="网站、文章等资源名，最多 25 字" maxLength={60} allowClear />
            </FormItem>
            <FormItem
              label="描述"
              name="desc"
              rules={[
                {
                  required: true,
                  message: '请输入描述',
                },
              ]}
            >
              <Input placeholder="用一句话简单介绍资源，最多 80 字" maxLength={80} allowClear />
            </FormItem>
            <FormItem
              label="链接"
              name="url"
              rules={[
                {
                  required: true,
                  message: '请填写链接',
                },
              ]}
            >
              <Input placeholder="便于找到资源的网址，http(s) 开头" allowClear />
            </FormItem>
            <FormItem
              label="资源标签"
              name="tips"
              rules={[
                {
                  required: true,
                  message: '至少填写 1 个标签',
                },
                {
                  max: 5,
                  type: 'array',
                  message: '至多选择 5 个标签',
                },
              ]}
            >
              <Select
                mode="multiple"
                allowClear
                style={{
                  width: '100%',
                }}
                filterOption={false}
              >
                {tags}
              </Select>
            </FormItem>
            <FormItem
              label="图标"
              name="icon"
              tooltip={{ title: '正方形图标展示效果最佳', placement: 'topLeft' }}
            >
              <UploadPic />
            </FormItem>
            <FormItem
              {...submitFormLayout}
              style={{
                marginTop: 32,
              }}
            >
              <Row gutter={24}>
                <Col span={16}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    onClick={() => doSubmit(resource)}
                    // block
                    // loading={submitting}
                    // disabled={submitting || disabled}
                  >
                    {/* {submitting ? '提交中' : '提交'} */}提交
                  </Button>
                </Col>
                <Col span={8}>
                  {/* <Tooltip
                    placement="topRight"
                    overlayStyle={{ minWidth: 260 }}
                    title={
                      <ResourceCard
                        resource={previewResource}
                        loading={!previewResource}
                        showActions={false}
                      />
                    }
                  > */}
                  {/* <Button>预览</Button> */}
                  {/* </Tooltip> */}
                </Col>
              </Row>
            </FormItem>
          </Form>
        </Card>
      </PageContainer>
    </div>
  );
};

export default AddResource;
